package com.miplus.ccrm.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JTimer {
    public boolean isRunning = false;
    public long waitMillisecond=1000;
    private boolean m_bExit=true;

    private Thread myThread=null;
    protected final JThreadEvent hEvent=new JThreadEvent();

    //getClass()可以打调用的父类ID
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public JTimer()
    {

    }

    //JTimer如果执行
    public int StartTimer(String name,int s)
    {
        if(isRunning){
            logger.info("JTimer.Start:{} Running..",name);
            return 0;
        }
        waitMillisecond=s*1000;
        logger.info("JTimer.Start({}):{}..",name,s);
        m_bExit=false;
        isRunning=false;

        myThread=new Thread(new Runnable(){
            @Override
            public void run() {
                OnRun();
            }
        }, name);
        myThread.start();

        return 0;
    }

    public void StopTimer()
    {
        if(m_bExit) return;

        m_bExit=true;
        try {
            logger.info("JTimer.Stop:{}..",myThread.getName());
            hEvent.SetEvent();
        }
        catch (Exception e){
            logger.error("JTimer.SetEvent Error:{}",e.toString());
        }
    }

    public void OnRun()
    {
        logger.info("JTimer.Running:{}..",myThread.getName());

        isRunning=true;
        while(!m_bExit&&isRunning){
            try {
                hEvent.WaitOne(waitMillisecond);
            }
            catch (Exception e){
                logger.error("JTimer.WaitOne Error:{}",e.toString());
                m_bExit=true;
            }
            if(m_bExit) break;
            isRunning=OnTimer();
        }

        isRunning=false;
        logger.info("JTimer.Done.");
    }

    public boolean OnTimer()
    {
        //此函数需要重载
        logger.info("JTimer.OnTimer..");
        return false;
    }

    public long getId()
    {
        if(myThread==null) return 0;

        return myThread.getId();
    }
}
